from typing import Optional

from selenium.webdriver.common.by import By


# 定位对象
class Xpath:
    def __init__(
            self,
            xpath_exp: str,
            name: str,
            many: Optional[bool] = False,
    ):
        self.xpath_exp = xpath_exp  # 固定使用 xpath
        self.name = name  # 当前定位名称
        self.many = many  # 是否为一组元素

    @property
    def locator(self) -> tuple[str, str]:
        return By.XPATH, self.xpath_exp

    @classmethod
    def from_dict(cls, name, locator_info: dict):
        try:
            if not (xpath_exp := locator_info["xpath"]):
                raise ValueError(f"{name} 中 xpath 表达式未配置")
        except KeyError:
            raise ValueError(f"{name}中未配置xpath") from None
        try:
            if not (many := locator_info["many"]) not in (True, False):
                raise ValueError(f"{name} 中 many 配置项只能为 True 或者 False")
        except KeyError:
            raise ValueError(f"{name} 中未配置many")

        return cls(xpath_exp, name, many)
